package com.xxx.gaoxi.controller;

import com.google.gson.Gson;
import com.xxx.gaoxi.common.service.facade.entity.UserEntity;
import com.xxx.gaoxi.common.service.facade.entity.dto.RetDTO;
import com.xxx.gaoxi.common.service.facade.entity.req.LoginReq;
import com.xxx.gaoxi.common.service.facade.exception.BizException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * Description
 * ...
 * DATE 2018/4/2.
 *
 * @author Mr. Chun.
 */

@RestController
@RequestMapping("/account")
public class AccountController {
    private static final Logger logger = LoggerFactory.getLogger(AccountController.class);

    @Autowired
    private RestTemplate restTemplate;

    @PostMapping("/login")
    public RetDTO login(@RequestParam("userName") String userName, @RequestParam("password") String password) {
        if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)) {
            return new RetDTO(400, "参数无效");
        }

        LoginReq req = new LoginReq();
        req.setUserName(userName);
        req.setPassword(password);

        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            MultiValueMap<String, String> params= new LinkedMultiValueMap<String, String>();
            params.add("userName", userName);
            params.add("password", password);
            HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers);
            ResponseEntity<String> response = restTemplate.postForEntity("http://localhost:8081/user/login", request, String.class);
            String json = response.getBody();
            System.out.println(json);
            UserEntity entity = new Gson().fromJson(json, UserEntity.class);
            if (entity.getId() > 0) {
                return RetDTO.getSuccess(entity);
            } else {
                return RetDTO.getError(400);
            }
        } catch (Exception e) {
            logger.info("func: {}, e: {}", "login", e.getMessage());
            throw new BizException(e.getMessage());
        }
    }
}
